package org.vehicle.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.vehicle.common.MyConstant;
import org.vehicle.entity.DataRecordInfo;
import org.vehicle.entity.security.MyUserDetail;
import org.vehicle.service.DataRecordInfoService;
import org.vehicle.util.CommonUtil;
import org.vehicle.util.FtpUtil;

@Controller
public class DataRecordInfoController {
	
    @Resource
    private DataRecordInfoService dataRecordInfoService;
	
    /**
     * 人员信息页面
     * @param req
     * @param model
     * @return
     */
	@RequestMapping("personInfo")
	public String personInfo(HttpServletRequest req, Model model){
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		model.addAttribute("manager", ud);
		return "personInfo";
	}
	
	/**
	 * 人员告警信息页面
	 * @param req
	 * @param model
	 * @return
	 */
	@RequestMapping("personAlertInfo")
	public String personAlertInfo(HttpServletRequest req, Model model){
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		model.addAttribute("manager", ud);
		return "personAlertInfo";
	}
	
	/**
     * 统计
     * @param req
     * @param model
     * @return
     */
	@RequestMapping("statistical")
	public String statistical(HttpServletRequest req, Model model){
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		model.addAttribute("manager", ud);
		return "statisticalInit";
	}
    /**
     * 获取人员信息列表
     * @param request
     * @return
     */
    @RequestMapping("/getDataRecordInfoList")
    @ResponseBody
    public Map<String, Object> getDataRecordInfoList(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
        String currentPage = request.getParameter("curr");
        String pageSize = request.getParameter("pageSize");
        String vehicleLicense = request.getParameter("vehicleLicense");
        String personName = request.getParameter("personName");
        String startTime=request.getParameter("startTime");
		String endTime=request.getParameter("endTime")==null?null:request.getParameter("endTime")+" 23:59:59";
    	MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("startPage", (Integer.parseInt(currentPage) - 1) * Integer.parseInt(pageSize));
            paramMap.put("pageSize", Integer.parseInt(pageSize));
            paramMap.put("vehicleLicense", vehicleLicense);
            paramMap.put("personName", personName);
            paramMap.put("startTime", startTime);
            paramMap.put("endTime", endTime);
            if(ud.getManagerType()!=MyConstant.MANAGER_TYPE_ROOT){
            	paramMap.put("organizationInfoId", ud.getOrganizationInfoId());
            }
            map = dataRecordInfoService.getDataRecordInfoList(paramMap);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 获取人员告警信息列表
     * @param request
     * @return
     */
    @RequestMapping("/getPersonAlertList")
    @ResponseBody
    public Map<String, Object> getPersonAlertList(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
        String currentPage = request.getParameter("curr");
        String pageSize = request.getParameter("pageSize");
        String vehicleLicense = request.getParameter("vehicleLicense");
        String personName = request.getParameter("personName");
        String startTime=request.getParameter("startTime");
		String endTime=request.getParameter("endTime")==null?null:request.getParameter("endTime")+" 23:59:59";
    	MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("startPage", (Integer.parseInt(currentPage) - 1) * Integer.parseInt(pageSize));
            paramMap.put("pageSize", Integer.parseInt(pageSize));
            paramMap.put("vehicleLicense", vehicleLicense);
            paramMap.put("personName", personName);
            paramMap.put("startTime", startTime);
            paramMap.put("endTime", endTime);
            if(ud.getManagerType()!=MyConstant.MANAGER_TYPE_ROOT){
            	paramMap.put("organizationInfoId", ud.getOrganizationInfoId());
            }
            map = dataRecordInfoService.getPersonAlertList(paramMap);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return map;
    }
    
    @RequestMapping("personMapInfo")
	public String personMapInfo(HttpServletRequest req, Model model){
		req.setAttribute("personId", req.getParameter("personId"));
		return "personMap";
	}
    /**
     * 获取人员信息
     * @param request
     * @return
     */
    @RequestMapping("/getPersonInfo")
    @ResponseBody
    public Map<String, Object> getPersonInfo(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
        String personId = request.getParameter("key");
		try {
			DataRecordInfo dataRecordInfo=dataRecordInfoService.selectByPrimaryKey(Long.parseLong(personId));
			map.put("dataRecordInfo", dataRecordInfo);
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 获取总检查人数
     * @param request
     * @return
     */
    @RequestMapping("/getCheckCount")
    @ResponseBody
    public Map<String, Object> getCheckCount(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    	String todayDate = request.getParameter("todayDate");
    	try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            if(ud.getManagerType() == MyConstant.MANAGER_TYPE_ADMIN) {
            	paramMap.put("managerType", ud.getManagerType());
            	paramMap.put("organizationInfoId", ud.getOrganizationInfoId());
            }
            paramMap.put("todayDate", todayDate);
            map = dataRecordInfoService.getCheckPersonCount(paramMap);
        } catch (Exception e) {
        	e.printStackTrace();
        }
    	return map;
    }
    
    /**
     * 获取总告警人数
     * @param request
     * @return
     */
    @RequestMapping("/getAlertCount")
    @ResponseBody
    public Map<String, Object> getAlertCount(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    	String todayDate = request.getParameter("todayDate");
    	try {
    		Map<String, Object> paramMap = new HashMap<String, Object>();
            if(ud.getManagerType() == MyConstant.MANAGER_TYPE_ADMIN) {
            	paramMap.put("managerType", ud.getManagerType());
            	paramMap.put("organizationInfoId", ud.getOrganizationInfoId());
            }
            paramMap.put("todayDate", todayDate);
    		map = dataRecordInfoService.getAlertCount(paramMap);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	return map;
    }
    
    /**
     * 获取总处理人数
     * @param request
     * @return
     */
    @RequestMapping("/getDisposeCount")
    @ResponseBody
    public Map<String, Object> getDisposeCount(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    	try {
    		Map<String, Object> paramMap = new HashMap<String, Object>();
            if(ud.getManagerType() == MyConstant.MANAGER_TYPE_ADMIN) {
            	paramMap.put("managerType", ud.getManagerType());
            }
    		map = dataRecordInfoService.getDisposeCount(paramMap);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	return map;
    }
    
    /**
     * 获取每个检查站检查的人数和告警数
     * @param request
     * @return
     */
    @RequestMapping("/getStatistics")
    @ResponseBody
    public Map<String, Object> getStatistics(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = dataRecordInfoService.getStatistics();
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 获取每个检查站当天检查的人数
     * @param request
     * @return
     */
    @RequestMapping("/getTodayPersonCount")
    @ResponseBody
    public Map<String, Object> getTodayPersonCount(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = dataRecordInfoService.getTodayPersonCount();
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 获取30天内每天的检查人数
     * @param request
     * @return
     */
    @RequestMapping("/getSevenDaysPersonCount")
    @ResponseBody
    public Map<String, Object> getSevenDaysPersonCount(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    	try {
    		Map<String, Object> paramMap = new HashMap<String, Object>();
            if(ud.getManagerType() == MyConstant.MANAGER_TYPE_ADMIN) {
//            	paramMap.put("managerType", ud.getManagerType());
            	paramMap.put("organizationInfoId", ud.getOrganizationInfoId());
            }
    		map = dataRecordInfoService.getSevenDaysPersonCount(paramMap);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	return map;
    }
    
    /**
     * 获取30天内每天的检查车辆数
     * @param request
     * @return
     */
    @RequestMapping("/getSevenDaysVehicleLicenseCount")
    @ResponseBody
    public Map<String, Object> getSevenDaysVehicleLicenseCount(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    	try {
    		Map<String, Object> paramMap = new HashMap<String, Object>();
    		if(ud.getManagerType() == MyConstant.MANAGER_TYPE_ADMIN) {
    			paramMap.put("organizationInfoId", ud.getOrganizationInfoId());
    		}
    		map = dataRecordInfoService.getSevenDaysVehicleLicenseCount(paramMap);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	return map;
    }
    /**
     * 获取照片
     * @param req
     * @param res
     */
    @RequestMapping("/getPhoto")
	public void getGoodsPhoto(HttpServletRequest req,HttpServletResponse res){
		String photoStr=req.getParameter("photoUrl");
		OutputStream os =null;
		InputStream is =null;
		FTPClient ftpClient =null;
		try {
			res.setContentType("image/jpg");
			ftpClient=FtpUtil.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"));
			if(photoStr.lastIndexOf("/")>0){
				FtpUtil.changeWorkingDirectory(photoStr.substring(0, photoStr.lastIndexOf("/")), ftpClient);
				is=FtpUtil.retrieveFileStream(photoStr.substring(photoStr.lastIndexOf("/")+1,photoStr.length()), ftpClient);
			}else{
				is=FtpUtil.retrieveFileStream(photoStr, ftpClient);
			}
			os=res.getOutputStream();
			byte[] buf = new byte[1024];
            while (true) {
                int read = 0;
                if (is != null) {
                    read = is.read(buf);
                }
                if (read == -1) {
                    break;
                }
                os.write(buf, 0, read);
            }
            os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(ftpClient!=null){
					FtpUtil.closeConnection(ftpClient);
				}
			} catch (Exception e) {
				ftpClient=null;
			} 
			try {
				os.close();
			} catch (IOException e) {
				os=null;
			} 
			try {
				is.close();
			} catch (IOException e) {
				is=null;
			}
		}
	}
    
}
